package work.huangxin.share.redisListenter;
//
//import org.springframework.data.redis.connection.Message;
//import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
//import org.springframework.data.redis.listener.RedisMessageListenerContainer;
//import org.springframework.stereotype.Component;
//
//
//@Component
//public class KeyExpiredListener extends KeyExpirationEventMessageListener {
//
//    public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
//        super(listenerContainer);
//    }
//
//    /**
//     * 针对redis数据失效事件，进行数据处理
//     *
//     * @param message
//     * @param pattern
//     */
//    @Override
//    public void onMessage(Message message, byte[] pattern) {
//        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
//        String expiredKey = message.toString();
//        byte[] body = message.getBody();
//        System.out.println(expiredKey + "过期" + "body:" + message.getBody().toString());
//    }
//}


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import work.huangxin.share.constant.RedisConstant;
import work.huangxin.share.service.AdminUserService;

@Component
public class KeyExpiredListener implements MessageListener {

    @Autowired
    private AdminUserService adminUserService;


    /**
     * 对redis数据失效事件，进行数据处理
     *
     * @param message 收到的消息内容
     * @param pattern 订阅的模式
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        if (expiredKey.startsWith(RedisConstant.USER_BLOCK_LIST)) {
                Integer userId =  Integer.parseInt(expiredKey.substring(RedisConstant.USER_BLOCK_LIST.length()));
            //在这里处理过期事件，将拉黑的用户从数据库中删除，并且设置 allow = 1
            adminUserService.unlockUserAndAllow(userId);
        }
    }
}